package com.wwj.core.pay.weixin;

import com.wwj.core.pay.entity.PayNotifyData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.XML;


/**
 * Created by Administrator on 2015/7/29.
 */
public class PayNotifyTemplate {

    private static Log logger = LogFactory.getLog(PayNotifyTemplate.class);

    private PayNotifyData payNotifyData = new PayNotifyData();

    public PayNotifyTemplate(String notifyXml) {
    	//手写解析支付回调报文，报文实例如下
    	/** <xml><appid><![CDATA[wxb89aea317d4af260]]></appid>
			<bank_type><![CDATA[CFT]]></bank_type>
			<cash_fee><![CDATA[1]]></cash_fee>
			<fee_type><![CDATA[CNY]]></fee_type>
			<is_subscribe><![CDATA[N]]></is_subscribe>
			<mch_id><![CDATA[1373505702]]></mch_id>
			<nonce_str><![CDATA[f5qn01mf40f1qb6iheat3ag36ocpvfpu]]></nonce_str>
			<openid><![CDATA[ooy-swM5W-kevJ-7xcKAEPKfBOiE]]></openid>
			<out_trade_no><![CDATA[1113971254128640441]]></out_trade_no>
			<result_code><![CDATA[SUCCESS]]></result_code>
			<return_code><![CDATA[SUCCESS]]></return_code>
			<sign><![CDATA[B5F20D31CAC83D6EA01DE99C50CAB753]]></sign>
			<time_end><![CDATA[20160923104412]]></time_end>
			<total_fee>1</total_fee>
			<trade_type><![CDATA[JSAPI]]></trade_type>
			<transaction_id><![CDATA[4006902001201609234685734261]]></transaction_id>
			</xml>**/
    	
    	boolean isValid = Signature.checkIsSignValidFromResponseString(notifyXml);
    	if (isValid) {
	        org.json.JSONObject jsonObject = null;
	        try {
	        	jsonObject = XML.toJSONObject(notifyXml);
	        } catch (JSONException e) {
	            e.printStackTrace();
	        }
	    	try{
	    		org.json.JSONObject Object = (org.json.JSONObject) jsonObject.get("xml");
	    		logger.info("xml里内容:"+Object);
	    		payNotifyData.setAppid(Object.get("appid").toString());
	    		payNotifyData.setBank_type(Object.get("bank_type").toString());
	    		payNotifyData.setCash_fee(Object.get("cash_fee").toString());
	    		payNotifyData.setFee_type(Object.get("fee_type").toString());
	    		payNotifyData.setIs_subscribe(Object.get("is_subscribe").toString());
	    		payNotifyData.setMch_id(Object.get("mch_id").toString());
	    		payNotifyData.setNonce_str(Object.get("nonce_str").toString());
	    		payNotifyData.setOpenid(Object.get("openid").toString());
	    		payNotifyData.setOut_trade_no(Object.get("out_trade_no").toString());
	    		payNotifyData.setResult_code(Object.get("result_code").toString());
	    		payNotifyData.setReturn_code(Object.get("return_code").toString());
	    		payNotifyData.setSign(Object.get("sign").toString());
	    		payNotifyData.setTime_end(Object.get("time_end").toString());
	    		payNotifyData.setTotal_fee(Object.get("total_fee").toString());
	    		payNotifyData.setTrade_type(Object.get("trade_type").toString());
	    		payNotifyData.setTransaction_id(Object.get("transaction_id").toString());
	    	}catch(Exception e){
	    		logger.error("json串转json对象时发生异常,json串="+notifyXml);
	    		throw new RuntimeException("json串转json对象时发生异常,json串="+notifyXml,e);
	    	}
    	}
    }

    public String execute(PaySuccessCallBack successCallBack) {
        ResponseData responseData = new ResponseData();
        if (payNotifyData == null) {
            responseData.setReturn_code("FAIL");
            responseData.setReturn_msg("签名错误");

            return XMLParser.toXML(responseData);
        }
        logger.debug("receive data from wechat:" + payNotifyData );
        if("SUCCESS".equals(payNotifyData.getReturn_code()) && "SUCCESS".equals(payNotifyData.getResult_code())) {

            if (successCallBack != null) {
                try {
                    successCallBack.onSuccess(payNotifyData);
                    responseData.setReturn_code("SUCCESS");
                    responseData.setReturn_msg("OK");
                } catch (Exception e) {
                    responseData.setReturn_code("FAIL");
                    responseData.setReturn_msg(e.getMessage());
                }

            }
        }

        return XMLParser.toXML(responseData);

    }


}
